package com.yunhuajinfu.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.yunhuajinfu.R;
import com.yunhuajinfu.activity.LoginActivity;
import com.yunhuajinfu.activity.SeetingsActivity;
import com.yunhuajinfu.activity.TouZiDetailsActivity;
import com.yunhuajinfu.banner.CycleViewPager;
import com.yunhuajinfu.banner.ViewFactory;
import com.yunhuajinfu.base.BaseFragment;
import com.yunhuajinfu.entity.ADInfo;
import com.yunhuajinfu.entity.BorrowList;
import com.yunhuajinfu.http.HttpCallBack;
import com.yunhuajinfu.http.HttpUtils;
import com.yunhuajinfu.mian.Config;
import com.yunhuajinfu.response.BannerRes;
import com.yunhuajinfu.response.HomeIndexRes;
import com.yunhuajinfu.tool.SharedPreferencesUtils;
import com.yunhuajinfu.util.DensityUtil;
import com.yunhuajinfu.view.CircleProgressViews;
import com.yunhuajinfu.view.MainTitleBar;
import com.yunhuajinfu.view.swipetoloadlayout.base.OnRefreshListener;
import com.yunhuajinfu.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页 推荐
 */
public class HomeFragment extends BaseFragment {
    @Bind(R.id.titlebar)
    MainTitleBar titlebar;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.circle_progress)
    CircleProgressViews mCircleProgressView;
    @Bind(R.id.tv_borrowTitle)
    TextView tvBorrowTitle;
    @Bind(R.id.tv_minAmount)
    TextView tvMinAmount;
    @Bind(R.id.tv_borrowTimeLimit)
    TextView tvBorrowTimeLimit;
    @Bind(R.id.tv_isDay)
    TextView tvIsDay;
    @Bind(R.id.iv_goumai)
    TextView mivGouMai;
    @Bind(R.id.tv_context)
    TextView tv_context;
    //
    View view;
    //
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private CycleViewPager cycleViewPager;

    //
    HomeIndexRes homeres;
    BannerRes bannerres;
    //首页面返回的数据
    private BorrowList borroInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {
        titlebar.setTitleBar(0, "雲化金服", R.mipmap.login_head);
        titlebar.setTitleBarTextColor(getResources().getColor(R.color.black_5));
        //天坑啊 getChildFragmentManager
        cycleViewPager = (CycleViewPager) getChildFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content);
        configImageLoader();

    }

    @Override
    protected void initView() {
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
//                 //获取首页收据
                views.clear();
                infos.clear();
                getData();
            }
        });
    }

    @Override
    protected void setData() {
        getData();

    }

    private void getData() {
        getBannerData();
        mCircleProgressView.setRadius(DensityUtil.dip2px(getContext(), 130));
        mCircleProgressView.setStokewidth(DensityUtil.dip2px(getContext(), 20));
        mCircleProgressView.setTextSize(DensityUtil.sp2px(getContext(), 16));
        mCircleProgressView.setColor(getContext().getResources().getColor(R.color.title_line), getContext().getResources().getColor(R.color.bule), getContext().getResources().getColor(R.color.black_6));
        mCircleProgressView.setSpeed(10);
        mCircleProgressView.setCenterText("年化利率");
        mCircleProgressView.setTopText("0.00%");
        mCircleProgressView.setmTextTopSize(DensityUtil.sp2px(getContext(), 30));
        mCircleProgressView.setBottomText("利率高 收益稳");
        mCircleProgressView.setmTextBottmSize(DensityUtil.sp2px(getContext(), 12));
//      mCircleProgressView.setProgress(80);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.iv_goumai, R.id.titlebar_iv_rignt_img})
    @Override
    protected void widgetClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goumai:   //立即投资

                //判断是否登录了  因为在下一个页面统一判断是否登录了
                Intent intent = new Intent(getActivity(), TouZiDetailsActivity.class);
                if (null != borroInfo) {
                    intent.putExtra("borroInfo", borroInfo);
                    intent.putExtra("type", "1000");
                    startActivityForResult(intent, 1000);
                }

                break;

            case R.id.titlebar_iv_rignt_img:   //登录
                if (SharedPreferencesUtils.getInstance().isLogin(getActivity(), "userAccount")) {
                    startActivity(new Intent(getActivity(), SeetingsActivity.class));
                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }

                break;

            default:
        }
    }

    /**
     * 获取Banner数据
     */
    private void getBannerData() {
        HttpUtils.get(Config.BANNER, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (null != result) {
                    try {
                        bannerres = new BannerRes(new JSONObject(result.toString()));

                        for (int i = 0; i < bannerres.getBannerList().size(); i++) {
                            ADInfo info = new ADInfo();
                            info.setUrl(bannerres.getBannerList().get(i).getBannerUrl());
                            infos.add(info);

                        }


                        //获取首页收据
                        getIndexHomeData();

                        //
                        cycleViewPager.setTv_context(tv_context);
                        // 将最后一个ImageView添加进来
                        views.add(ViewFactory.getImageView(getActivity(), infos.get(infos.size() - 1).getUrl()));
                        for (int i = 0; i < infos.size(); i++) {
                            views.add(ViewFactory.getImageView(getActivity(), infos.get(i).getUrl()));

                        }
                        // 将第一个ImageView添加进来
                        views.add(ViewFactory.getImageView(getActivity(), infos.get(0).getUrl()));
                        //第一次进来的时候显示
                        tv_context.setText(infos.get(0).getUrl());

                        // 设置循环，在调用setData方法前调用
                        cycleViewPager.setCycle(true);

                        // 在加载数据前设置是否循环
                        cycleViewPager.setData(views, infos, mAdCycleViewListener);
                        //设置轮播
                        cycleViewPager.setWheel(true);

                        // 设置轮播时间，默认5000ms
                        cycleViewPager.setTime(2000);
                        //设置圆点指示图标组居中显示，默认靠右
                        cycleViewPager.setIndicatorCenter();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }


            @Override
            public void onError(String code, String message) {

                mRefresh.setRefreshing(false);
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 获取首页数据
     */
    private void getIndexHomeData() {
        //

        HttpParams param = new HttpParams();


        HttpUtils.post(Config.HOME_INDEX, param, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mRefresh.setRefreshing(false);
                if (null != result) {
                    try {
                        homeres = new HomeIndexRes(new JSONObject(result.toString()));
                        if (homeres.getBorrowList().size() > 0) {

                        borroInfo = homeres.getBorrowList().get(0);
                        tvBorrowTitle.setText(borroInfo.getBorrowTitle());
                        tvMinAmount.setText(borroInfo.getMinAmount());
                        tvBorrowTimeLimit.setText(borroInfo.getBorrowTimeLimit());
                        //
//                      mCircleProgressView.setCenterText(borroInfo.getAnnualInterestRate());
                        mCircleProgressView.setTopText(borroInfo.getAnnualInterestRate() + "%");
                        //加息算法
//                        if (borroInfo.getInterestGrowth().equals("0.00")) {
//                            mCircleProgressView.setTopText(subZeroAndDot(borroInfo.getAnnualInterestRate())+"%");
//                        } else {
//                            mCircleProgressView.setTopText(subZeroAndDot(StringValuesjian(borroInfo.getAnnualInterestRate().toString().trim(), borroInfo.getInterestGrowth().toString().trim())) + "% +" + subZeroAndDot(borroInfo.getInterestGrowth().toString().trim())+"%");
//
//                        }

                        int pro = StringValueOfInt(borroInfo.getTenderSum(), borroInfo.getBorrowSum());
                        mCircleProgressView.setProgress(pro);
                        mCircleProgressView.startProgress();

                        if (borroInfo.getIsDay().equals("1")) {
                            tvIsDay.setText("天");
                        } else {
                            tvIsDay.setText("个月");
                        }


                        //判断投资状态
                        if (null != borroInfo) {
                            if (borroInfo.getEndStart().equals("1")) {   //可点击
                                mivGouMai.setClickable(true);
                            } else {
                                mivGouMai.setText("筹募期已结束");
                                mivGouMai.setClickable(false);
//                            Toast.makeText(getActivity(), "筹募期已结束", Toast.LENGTH_SHORT).show();
                            }

                        }


                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }

            @Override
            public void onError(String code, String message) {
                mRefresh.setRefreshing(false);
            }
        });

    }


    /**
     * Stirng 转int
     *
     * @param currentnumber
     * @param sum
     * @return
     */

    public int StringValueOfInt(String currentnumber, String sum) {
        float m = Float.valueOf(currentnumber);
        float mm = Float.valueOf(sum);
        return (int) ((m / (int) mm) * 100);
    }

    /**
     * 及时更新homeFragment数据
     */
    public void update() {
        homeres = null;
        getIndexHomeData();
    }

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.banner) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.banner) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.banner) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
//                Toast.makeText(getActivity(), info.getContent(), Toast.LENGTH_SHORT).show();
            }

        }

    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1000:
                getIndexHomeData();
                break;
            default:

        }

    }


    /**
     * @param num
     * @param min
     * @return String转float相减
     */
    public String StringValuesjian(String num, String min) {
        float floatnum = Float.parseFloat(num);
        float floatmin = Float.parseFloat(min);
        float values = floatnum - floatmin;
        try {
            return String.format("%.2f", values);
        } catch (Exception e) {

            return "0.00";
        }

    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

}

